package cn.zhentao.controller;

import cn.zhentao.mapper.RoleMapper;
import cn.zhentao.mapper.UsersMapper;
import cn.zhentao.pojo.*;
import cn.zhentao.service.*;
import cn.zhentao.util.HttpUtils;
import cn.zhentao.util.JwtService;
import cn.zhentao.util.Result;
import cn.zhentao.util.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    IUsersService usersService;
    @Autowired
    IOrdersService ordersService;
    @Autowired
    IDeliveryMenService deliveryMenService;
    @Autowired
    IOrderAssignmentsService orderAssignmentsService;
    @Autowired
    IUserAddressesService userAddressesService;
    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IUserroleService userroleService;
    //用户的所有订单(已获取地址和配送员)

    @PostMapping("dingDanSel")
    public List<Orders> dingDanSel(Integer userId){
        List<Orders> ordersList=new ArrayList<>();
        List<Orders> list = ordersService.list();
        for (Orders orders : list) {
            if(orders.getUserId()==userId){
                List<OrderAssignments> orderAssignments = orderAssignmentsService.list();
                for (OrderAssignments orderAssignment : orderAssignments) {
                    DeliveryMen deliveryMen = deliveryMenService.getById(orderAssignment.getDeliverymanId());
                    orders.setDeliveryname(deliveryMen.getName());
                    UserAddresses userAddresses = userAddressesService.getById(orders.getAddressId());
                    orders.setMudidi3(userAddresses.getAddress());
                    ordersList.add(orders);
                }
            }
        }
        List<Orders> lastFour = ordersList.stream()
                .skip(Math.max(0, ordersList.size() - 4))
                .collect(Collectors.toList());
        return lastFour;
    }

    //    用户个人信息
    @PostMapping("userSel")
    public Users userSel(Integer id){
        Users users = usersService.getById(id);
        return users;
    }
    //获取用户地址
    @PostMapping("addressSel")
    public List<UserAddresses> addressSel(Integer userId){
        List<UserAddresses> list=new ArrayList<>();
        List<UserAddresses> addressesList = userAddressesService.list();
        for (UserAddresses userAddresses : addressesList) {
            if(userAddresses.getUserId()==userId){
                list.add(userAddresses);
            }
        }
        return list;
    }
    //用户创建订单

    @RequestMapping("orderAdd")
    public String orderAdd(@RequestBody Orders orders){
        ordersService.save(orders);
        return "添加订单成功";
    }
    //新增收货地址
    @PostMapping("addressAdd")
    public String addressAdd(@RequestBody UserAddresses userAddresses){
        userAddresses.setCreatedAt(new Date());
        userAddressesService.save(userAddresses);
        return "地址添加成功";
    }
    //用户订单取消
    @PostMapping("quXiao")
    public String quXiao(Integer id){
        Orders orders = ordersService.getById(id);
        System.err.println(orders);
        orders.setStatus(4);
        ordersService.updateById(orders);
        return "取消订单成功";
    }
    //删除用户地址
    @PostMapping("addressDel")
    public String addressDel(Integer id){
        userAddressesService.removeById(id);
        return "删除地址成功";
    }
    //用户密码修改


    //分页订单状态查询
    //查询
    @RequestMapping("findAllPage")
    public Result findAllPage(@RequestBody QueryPage queryPage){
        Page<Orders> page = ordersService.findAllPage(queryPage);
        return Result.OK(page);
    }
    //设置地址为默认
    @PostMapping("moRen")
    public void moRen(Integer id){
        UserAddresses addresses = userAddressesService.getById(id);
        addresses.setIsDefault(1);
        List<UserAddresses> list = userAddressesService.list();
        List<UserAddresses> userAddressesList=new ArrayList<>();
        for (UserAddresses userAddresses : list) {
            if(userAddresses.getUserId()==addresses.getUserId()){
                userAddressesList.add(userAddresses);
            }
        }
        if(addresses.getIsDefault()==1){
            for (UserAddresses userAddresses : userAddressesList) {
                userAddresses.setIsDefault(0);
                userAddressesService.updateById(userAddresses);
            }
        }
        userAddressesService.updateById(addresses);

    }
    //登录方法
    //全局的登录验证码
    int code;
    @RequestMapping("login")
    public Result login(@RequestBody Users users) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq(users.getUsername()!=null,"username", users.getUsername());
        Users user = usersMapper.selectOne(usersQueryWrapper);
        if(user==null){
            Users userByPhone = usersMapper.selectOne(new QueryWrapper<Users>().eq("phone", users.getUsername()));
            if(userByPhone!=null){
                //根据phone查询的userByPhone,让userByPhone赋给user
                user=userByPhone;
            }else {
                return Result.ERROR("用户不存在");
            }
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(users.getPassword(), user.getPassword());
        if (matches) {
            List<Userrole> id = userroleService.list(new QueryWrapper<Userrole>().eq("uid", user.getId()));
            if (id != null && id.size() > 0) {
                Role rid = roleMapper.selectOne((new QueryWrapper<Role>()).eq("rid", id.get(0).getRid()));
                user.setRname(rid.getRname());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("username", user.getUsername());
            map.put("nikename", user.getNickname());
            map.put("id", user.getId());
            map.put("rname", user.getRname());
            String token = JwtService.createToken(map);
            user.setToken(token);
            ThreadLocalUtil.set(token);
            return Result.OK(user);
        }
        return Result.ERROR("用户名或密码错误");
    }


    @RequestMapping("phonelogin")
    public Result phonelogin(@RequestBody Users users) {
        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq(users.getPhone()!=null,"phone", users.getPhone());
        Users user = usersMapper.selectOne(usersQueryWrapper);
        System.err.println("code"+code + "getCode" + users.getCode());
        int code1 = Integer.parseInt(users.getCode());
        if (code1 == code) {
            List<Userrole> id = userroleService.list(new QueryWrapper<Userrole>().eq("uid", user.getId()));
            if (id != null && id.size() > 0) {
                Role rid = roleMapper.selectOne((new QueryWrapper<Role>()).eq("rid", id.get(0).getRid()));
                user.setRname(rid.getRname());
            }
            HashMap<String, Object> map = new HashMap<>();
            map.put("username", user.getUsername());
            map.put("nikename", user.getNickname());
            map.put("id", user.getId());
            map.put("rname", user.getRname());
            String token = JwtService.createToken(map);
            user.setToken(token);
            ThreadLocalUtil.set(token);
            return Result.OK(user);
        }
        return Result.ERROR("用户名或密码错误");
    }
    //以精品服务打造精品API产品。
//vip优惠券，技术支持。请直接联系客服（vx同号）  18600814970。
//    @RequestMapping("phone1")
//    public Result phone1(String phone){
//        Random random = new Random();
//        int i = 100000 + random.nextInt(900000);
//        code = i;
//        String host = "https://dfsns.market.alicloudapi.com";
//        String path = "/data/send_sms";
//        String method = "POST";
//        String appcode = "051a9f6970f441f8a7941776ab670e32";
//        Map<String, String> headers = new HashMap<String, String>();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        //根据API的要求，定义相对应的Content-Type
//        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//        Map<String, String> querys = new HashMap<String, String>();
//        Map<String, String> bodys = new HashMap<String, String>();
//        bodys.put("content", "code:"+i);
//        bodys.put("template_id", "CST_ptdie100");  //注意，CST_ptdie100该模板ID仅为调试使用，调试结果为"status": "OK" ，即表示接口调用成功，然后联系客服报备自己的专属签名模板ID，以保证短信稳定下发
//        bodys.put("phone_number", phone);
//
//
//        try {
//            /**
//             * 重要提示如下:
//             * HttpUtils请从
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
//             * 下载
//             *
//             * 相应的依赖请参照
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
//             */
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
//            HttpEntity entity = response.getEntity();
//            String result = EntityUtils.toString(entity,"UTF-8");
//            System.out.println(result);
//            //获取response的body
//            //System.out.println(EntityUtils.toString(response.getEntity()));
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return  Result.OK();
//    }
    @RequestMapping("phone")
    public Result phone(@RequestParam("phone") String phone){
        Random random = new Random();
        int i = 100000 + random.nextInt(900000);
        code = i;
        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";
        String appcode = "051a9f6970f441f8a7941776ab670e32";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("content", "code:"+i);
        bodys.put("template_id", "CST_ptdie100");  //注意，CST_ptdie100该模板ID仅为调试使用，调试结果为"status": "OK" ，即表示接口调用成功，然后联系客服报备自己的专属签名模板ID，以保证短信稳定下发
        bodys.put("phone_number", phone);


        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity,"UTF-8");
            System.out.println(result);
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  Result.OK(code);
    }

    @RequestMapping("register")
    public Result register(@RequestBody Users users){
        users.setNickname(users.getUsername());
        String encode = new BCryptPasswordEncoder().encode(users.getPassword());
        users.setPassword(encode);
        users.setCreatedAt(new Date());
        List<Users> list = usersService.list();
        //用户名重复
        for (Users users1 : list) {
            if (users1 != null) {
                if (users1.getUsername().equals(users.getUsername())) {
                    return Result.ERROR("用户名重复");
                }
            }
        }
        for (Users users1 : list) {
            if (users1 != null) {
                if (users1.getPhone().equals(users.getPhone())) {
                    return Result.ERROR("手机号重复");
                }
            }
        }
        int code1 = Integer.parseInt(users.getCode());
        if( code1 == (code)){
        boolean save = usersService.save(users);
        Users username = usersMapper.selectOne(new QueryWrapper<Users>().eq("username", users.getUsername()));
        if (save) {
            Userrole userrole = new Userrole();
            userrole.setUid(username.getId());
            userrole.setRid(9);
            System.out.println(userroleService.save(userrole));
        }
            return (save)? Result.OK("注册成功") : Result.ERROR("注册失败");
        }
        return Result.ERROR("验证码错误");
    }

    //找回密码
    @RequestMapping("forgotPassword")
    public Result forgotPassword(@RequestBody Users users) {
        if (users != null) {
            int code1 = Integer.parseInt(users.getCode());
            if (!(code1 == code)) {
                return Result.ERROR("验证码错误");
            }
            String phone = users.getPhone();
            if(phone!=null){
                Users phone1 = usersMapper.selectOne(new QueryWrapper<Users>().eq("phone", users.getPhone()));
                if(phone1!=null){
                    phone1.setPassword(new BCryptPasswordEncoder().encode(users.getPassword()));
                    int i = usersMapper.updateById(phone1);
                    return  (i>0)?Result.OK("更新成功"):Result.ERROR("更新失败");
                }
            }
        }
        return Result.ERROR("更新失败");
    }

    //个人信息
    //Too
    @PostMapping("/GeRenXinXi")
    public Result geRenXinXi(Integer id) {
        Users byId = usersService.getById(id);
        return  Result.OK(byId);
    }

    //判断用户名是否重复
    @RequestMapping("onRepeatUserName")
    public Result onRepeatUserName(@RequestParam("username") String username){
        List<Users> list = usersService.list();
        boolean flag = false;
        for (Users users : list) {
            if(users.getUsername().equals(username)){
                flag = true;
                break;
            }
        }
        if(flag){
            return Result.ERROR("用户名重复");
        }else {
            return Result.OK("用户名未重名");
        }
    }
    //判断电话是否重复
    @RequestMapping("onRepeatPhone")
    public Result onRepeatPhone(@RequestParam("phone") String username){
        List<Users> list = usersService.list();
        boolean flag = false;
        for (Users users : list) {
            if(users.getPhone().equals(username)){
                flag = true;
                break;
            }
        }
        if(flag){
            return Result.ERROR("电话重复");
        }else {
            return Result.OK("电话未重复");
        }
    }
    //编辑个人信息
    @PostMapping("UpdateUser")
    public Result UpdateUser(Integer id,String username,String phone,String nickname){
        Users byId = usersService.getById(id);
        byId.setUsername(username);
        byId.setPhone(phone);
        byId.setNickname(nickname);
        usersService.updateById(byId);
        return Result.OK();
    }
    //修改密码
    @PostMapping("PasswordUpdate")
    public Result PasswordUpdate(Integer id,String oldPwd,String newPwd,String newPwd1){
        Users byId = usersService.getById(id);
        String newcode = new BCryptPasswordEncoder().encode(newPwd);
        String oldcode = new BCryptPasswordEncoder().encode(oldPwd);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(byId.getPassword(), oldcode);

        if(byId==null){
            return Result.ERROR("查询为空");
        }
        if(!matches){
            return Result.ERROR("与旧密码不一致");
        }
        if(!newPwd.equals(newPwd1)){
            return Result.ERROR("两次密码不一致");
        }
        if(oldPwd.equals(matches)){
            return Result.ERROR("旧密码与新密码不能一样");
        }

        byId.setPassword(newcode);
        usersService.updateById(byId);
        return Result.OK();
    }
}


